import 'dart:async';
import 'dart:io';
import 'dart:math';
import 'dart:ui' as ui;

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:image/image.dart' as img;
import 'dart:ui' as ui;

///图形相关工具

class ImageUtils {
  ImageUtils._();

  /// 获取图片的宽高
  /// [width] 希望的宽度  null 会使用svg本身的宽*屏幕密度
  /// [height] 希望的高度  null 会使用svg本身的高*屏幕密度
  static Future<ui.Image> loadSvgImage(BuildContext context, String assets, {double? targetWidth, double? targetHeight}) async {
    // 获取设备像素比（物理像素与逻辑像素的比例）
    // double dpr = ui.PlatformDispatcher.instance.views.first.devicePixelRatio;
    double dpr = MediaQuery.devicePixelRatioOf(context);
    final pictureInfo = await vg.loadPicture(SvgAssetLoader(assets), context);
    // 获取 SVG 原始尺寸
    final originalWidth = pictureInfo.size.width;
    final originalHeight = pictureInfo.size.height;
    // 将图片尺寸转换为物理像素尺寸
    final targetWidthPx = targetWidth != null ? targetWidth * dpr : (originalWidth * dpr);
    final targetHeightPx = targetHeight != null ? targetHeight * dpr : (originalHeight * dpr);

    // 计算缩放比例（保持宽高比）
    final widthRatio = targetWidthPx / originalWidth;
    final heightRatio = targetHeightPx / originalHeight;
    final scale = min(widthRatio, heightRatio);

    // 创建缩放后的画布
    final recorder = ui.PictureRecorder();
    final canvas = Canvas(recorder);
    canvas.scale(scale, scale);

    // 绘制 SVG 内容
    canvas.drawPicture(pictureInfo.picture);

    // 生成物理像素级别的图像
    final picture = recorder.endRecording();
    return picture.toImage(
      (originalWidth * scale).round(),
      (originalHeight * scale).round(),
    );
  }

  /// 获取图片
  /// 适用于大多数 UI 图片加载，尤其是需要重复使用（如列表项、图标），利用缓存提升性能
  static Future<ui.Image> loadImage(String asset, {double? targetWidth, double? targetHeight}) async {
    try {
      final provider = AssetImage(asset);
      final completer = Completer<ui.Image>();
      final stream = provider.resolve(ImageConfiguration.empty);
      final listener = ImageStreamListener((ImageInfo info, _) async {
        // print(" loadImage ${info}");
        if (targetWidth != null || targetHeight != null) {
          final result = await resizeImage(await convertImage(info.image), targetWidth, targetHeight);
          completer.complete(convertUiImage(result));
        } else {
          completer.complete(info.image);
        }
      });
      stream.addListener(listener);
      return completer.future.whenComplete(() => stream.removeListener(listener));
    } catch (e) {
      print("loadImage error $e");
      return Future.error(e);
    }
  }

  /// 获取图片 img.Image
  /// 适用于大多数 UI 图片加载，尤其是需要重复使用（如列表项、图标），利用缓存提升性能
  static Future<img.Image> loadImageX(String asset, {double? targetWidth, double? targetHeight}) async {
    try {
      final provider = AssetImage(asset);
      final completer = Completer<img.Image>();
      final stream = provider.resolve(ImageConfiguration.empty);
      final listener = ImageStreamListener((ImageInfo info, _) async {
        // print(" loadImage ${info}");
        if (targetWidth != null || targetHeight != null) {
          final result = await resizeImage(await convertImage(info.image), targetWidth, targetHeight);
          completer.complete(result);
        } else {
          completer.complete(await convertImage(info.image));
        }
      });
      stream.addListener(listener);
      return completer.future.whenComplete(() => stream.removeListener(listener));
    } catch (e) {
      print("loadImage error $e");
      return Future.error(e);
    }
  }

  /// 获取图片
  /// 当需要手动控制图片生命周期（如游戏纹理）、处理像素数据，或确保无缓存干扰时使用。
  static Future<ui.Image> loadImageNoCache(String asset) async {
    try {
      final data = await rootBundle.load(asset);
      final codec = await ui.instantiateImageCodec(data.buffer.asUint8List());
      final frame = await codec.getNextFrame();
      return frame.image;
    } catch (e) {
      print("loadImageNoCache error $e");
      return Future.error(e);
    }
  }

  Future<File> resizeImageFile(File file, int targetWidth, int targetHeight) async {
    final bytes = await file.readAsBytes();
    final image = img.decodeImage(bytes)!;

    // 调整尺寸（可设置是否保持比例）
    final resized = img.copyResize(
      image,
      width: targetWidth,
      height: targetHeight,
      maintainAspect: true, // 设为 true 则保持比例
    );

    // 保存为 JPEG（或使用 encodePng 保存为 PNG）
    final resizedBytes = img.encodeJpg(resized);
    return File('${file.path}_resized.jpg')..writeAsBytesSync(resizedBytes);
  }

  /// 缩放图片核心逻辑
  static Future<img.Image> resizeImage(img.Image original, double? targetWidth, double? targetHeight) async {
    final resized = img.copyResize(
      original,
      width: targetWidth?.toInt(),
      height: targetHeight?.toInt(),
      // 保持宽高比
      maintainAspect: true,
    );
    return resized;
  }

  /// 将image库图片转回Flutter的ui.Image
  static Future<ui.Image> convertUiImage(img.Image image) async {
    final completer = Completer<ui.Image>();
    ui.decodeImageFromPixels(
      image.getBytes(),
      image.width,
      image.height,
      ui.PixelFormat.rgba8888,
      (ui.Image image) => completer.complete(image),
    );
    return completer.future;
  }

  /// 将Flutter的ui.Image图片转回image库

  static Future<img.Image> convertImage(ui.Image original) async {
    // 获取原始像素数据（非 PNG 压缩格式）
    final byteData = await original.toByteData(format: ui.ImageByteFormat.rawRgba);
    final image = img.Image.fromBytes(
      width: original.width,
      height: original.height,
      bytes: byteData!.buffer,
      numChannels: 4,
    );
    return image;
  }
}
